package com.bobo.signature.ECDSA;

import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.interfaces.ECPrivateKey;
import java.security.interfaces.ECPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;
/**
 * Java的ECDSA数字签名
 * @author win7
 *
 */
public class ECDSAtest {

	public static String bobo="www.bobo.com";
	public static void main(String[] args) {
		JdkECDSA();
	}
	
	public static void JdkECDSA(){
		
		//1.初始化秘钥
		  try {
			KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("EC");
			keyPairGenerator.initialize(256);
			KeyPair keyPair= keyPairGenerator.generateKeyPair();
			ECPrivateKey ecPrivateKey=  (ECPrivateKey) keyPair.getPrivate();
			ECPublicKey  ecPublicKey=  (ECPublicKey) keyPair.getPublic();
		    //转换key秘钥
			PKCS8EncodedKeySpec pkcs8EncodedKeySpec=new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded());
			KeyFactory keyfatory=KeyFactory.getInstance("EC");
			PrivateKey privatekeysign= keyfatory.generatePrivate(pkcs8EncodedKeySpec);
		//2.执行签名	
			Signature signatureprivate=Signature.getInstance("SHA1withECDSA");
			signatureprivate.initSign(privatekeysign);
			signatureprivate.update(bobo.getBytes());
			byte[] result= signatureprivate.sign();
			System.out.println(HexBin.encode(result));
			 //转换key秘钥
			X509EncodedKeySpec x509EncodedKeySpec=new X509EncodedKeySpec(ecPublicKey.getEncoded());
			KeyFactory keypub=KeyFactory.getInstance("EC");
			PublicKey publickey= keypub.generatePublic(x509EncodedKeySpec);
		//3.验证签名		
			Signature signa=Signature.getInstance("SHA1withECDSA");
			signa.initVerify(publickey);
			signa.update(bobo.getBytes());
			boolean bool= signa.verify(result);//验证签名是否一致
			System.out.println(bool);
			
		} catch (NoSuchAlgorithmException | InvalidKeyException | InvalidKeySpecException | SignatureException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}
}
